<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class Tijinchang extends Commonti
{
    public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        $fid=1;$aid=$data["aid"];
        
            $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
            //print_r($res);exit;
            if($res["operateStatus"]=="success"){
                $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=1")->field("yd.id")->select();
                if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                        $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                }
                    try{
                        
                           
                            $up["id"]=$aid;
                            $up["status"]=8;
                        Db::table("cg_ti")->update($up);
                    }catch (\Exception $e){
        
                          return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
                        }
                      return json_encode(["msg"=>"","state"=>1]);
                  
                     
                }else{
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                }
      
        
    }
	//列表
    public function index($page=1,$list=20)
    {

       $request = Request::instance();


        $data = $request->post();
        $eid=Session::get("employee_id");
        $where = "t.type_id=1 and t.cuser=$eid ";
        if ($data) {
            if ($data["no"])
                $where .= "and t.sn={$data["no"]} ";
            if (trim($data["title"]))
                $where .= "and t.title like '%{$data["title"]}%' ";
            if ($data["status"])
                $where .= "and t.status={$data["status"]} ";
            if (trim($data["start"])) {
                $st = strtotime($data["start"]);
                $where .= "and t.ctime>=$st ";
            }
            if (trim($data["end"])) {
                $ed = strtotime($data["end"]) + 24 * 3600;
                $where .= "and t.ctime<$ed ";
            }
        } else {
            $data = ["no" => "", "title" => "", "status" => "", "start" => "", "end" => ""];
        }
        $sum = Db::table('cg_ti t')->where($where)->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $applys = Db::table('cg_ti t')->order("t.id desc")->where($where)->limit($start,$list)->select();

//        echo Db::table('cg_ti')->getLastSql();
       
        foreach($applys as $k=>$v){
            $v['cusername'] = Db::table('employee')->where(array('id'=>$v['cuser']))->value('em_name');
            $v['pusername'] = Db::table('employee')->where(array('id'=>$v['puser']))->value('em_name');
            $v['cate_title'] = Db::table('cg_ti_cate')->where(array('id'=>$v['cate_id']))->value('title');
            $v['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $v['ptime'] = date('Y-m-d H:i',$v['ptime']);
            switch ($v['status']){
                case 2:
                    $v['status_title'] = '已打回';
                    break;
                case 3:
                    $v['status_title'] = '区域领导审批';
                    break;
                case 4:
                    $v['status_title'] = '拆分人审批';
                    break;
                case 5:
                    $v['status_title'] = '集团领导审批';
                    break;
                case 6:
                    $v['status_title'] = '抄送';
                    break;
                case 7:
                    $v['status_title'] = '已归档';
                    break;
                case 8:
                    $v['status_title'] = '已作废';
                    break;
                case 9:
                    $v['status_title'] = '已否决';
                    break;
                default:
                    $v['status_title'] = '草稿';
            }

            //反馈完成之后才能显示核销按钮
            $v['fb_status'] = db('all_ti_feeback_list')->where(['type'=>1,'apply_id'=>$v['id']])->value('state');

            //查询状态在审核中的核销单是否存在
            $tiids = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')->where(['t.status'=>1,'ti_id'=>$v['id']])->column('t2.ti_id');
            $tiids = array_unique($tiids);
            $v['hx_status'] = in_array($v['id'],$tiids)?true:false;

            //查询状态在审核通过的核销单是否存在
            $tiids = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')->where(['t.status'=>2,'ti_id'=>$v['id']])->column('t2.ti_id');
            $tiids = array_unique($tiids);
            $v['yhx'] = in_array($v['id'],$tiids)?true:false;

            //正在核销或者已核销不能取消
            $v['zzhx'] = db('cg_ti_hexiao t')->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')->where(['t.status'=>1,'ti_id'=>$v['id']])->count();
            $applys[$k] = $v;
        }

        $this->assign("applys", $applys);

        $this->assign("data", $data);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);


        return $this->fetch();
    }

    //查询网点条码数
    public function chaTiaoMa(){
        $id = $this->request->param('id');
        $net_title = db('cg_net')->where('id',$id)->value('title');
        $where = [];
        $where['net_id'] = $id;
        $where['tuichang'] = 0;
        $data = db('cg_net_barcode')->where($where)
            ->count();
        $syxl = db('cg_net_barcode')->where($where)
            ->sum('shangYueXiaoLiang');
        $link = url('net/view6',['id'=>$id]);

        $tiaoMaShu = <<<EOF
        <p class="padding-10" data-id="{$id}">
            网点：<span class="colorRed">{$net_title}*</span>已进场：<a href="javascript:;" class="enter_t_arena"><span>{$data}</span>个条码</a>单店销量(万元/月)<input type="text" class="form-control" name="danDianXiaoLiang[{$id}]" value="{$syxl}"><a href="{$link}" target="_blank">去补录</a></p>
EOF;

        echo json_encode(['success'=>true,'tiaoMaShu'=>$tiaoMaShu]);
    }

    /**
     * 本次进场条码
     */
    public function benCiJinChangTiaoMa(){
        /*$netids = $this->request->post('data/a');
        $data = db('cg_net_barcode')->where('net_id','in',$netids)->where(['tuichang'=>0])->column('prod');
//        echo db('cg_ti')->getLastSql();
        $data = array_unique($data);*/


        $pro_ids = db('pro_products')->column('id');
        $pro_ids = array_unique($pro_ids);
        $li = [];
        foreach($pro_ids as $k=>$v){
            $pro_name = db('pro_products')->where('id',$v)->value('pro_name');
            $price = db('pro_price')->where('pid',$v)->field('retail_standard,factory')->find();
            $li[] = "<li data-id='{$v}' data-factory='{$price["factory"]}' data-retail_standard='{$price["retail_standard"]}'>{$pro_name}</li>";
        }
        $li = implode('',$li);
        echo <<<EOF
<ul>{$li}</ul>
EOF;

    }

    public function benCiJinChangTiaoMa_bak(){
        $netids = $this->request->post('data/a');
        $data = db('cg_net_barcode')->where('net_id','not in',$netids)->where(['tuichang'=>0])->column('prod');
//        echo db('cg_ti')->getLastSql();
        $data = array_unique($data);
        $c = db('cg_net_product_suplly')->where('net_id','in',$netids)->column('category');
        $c2 = [];
        foreach($c as $k=>$v){
            $v = explode(',',$v);
            $c2 = array_merge($c2,$v);
        }
        $c2 = array_unique($c2); //品类id

        $c2 = array_filter($c2,function($var){
            return $var?true:false;
        });

        $pro_ids = db('pro_products t')->join('pro_sku t2','t.sku_id=t2.id')->join('pro_series t3','t2.series_id=t3.id')->join('pro_category t4','t3.category_id=t4.id')->where('t4.id','in',$c2)->column('t.id');
        $pro_ids = array_unique($pro_ids);
        $pro_ids = array_diff($pro_ids,$data);
        $li = [];
        foreach($pro_ids as $k=>$v){
            $pro_name = db('pro_products')->where('id',$v)->value('pro_name');
            $price = db('pro_price')->where('pid',$v)->field('retail_standard,factory')->find();
            $li[] = "<li data-id='{$v}' data-factory='{$price["factory"]}' data-retail_standard='{$price["retail_standard"]}'>{$pro_name}</li>";
        }
        $li = implode('',$li);
        echo <<<EOF
<ul>{$li}</ul>
EOF;

    }

    /**
     * 费用计入部门
     */
    public function fyjrbm(){
        $data = db('cg_fijiruzd')->column('title');
//        echo db('cg_ti')->getLastSql();
        $data = array_unique($data);
        $li = [];
        foreach($data as $k=>$v){
            $pro_name = db('department')->where('id',$v)->value('de_name');
            $li[] = "<li data-id='{$v}'>{$pro_name}</li>";
        }
        $li = implode('',$li);
        echo <<<EOF
<ul>{$li}</ul>
EOF;
    }

    //选择我的常用网点
    public function selectMyNetGroup(){

        $where = [];
        $where['cuser'] = Session::get('employee_id');
        $count = Db::table('cg_ti_net_group t')->where($where)->count();
        $data = Db::table('cg_ti_net_group t')->order("t.id desc")->where($where)->paginate(10,$count);

//        echo Db::table('cg_ti')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $t = unserialize($v['net_id']);
            $t = implode(',',$t);
            $t = db('cg_net')->where('id','in',$t)->field('title,id')->select();
            $t2 = [];
            foreach($t as $kk=>$vv){
                $t2[] = $vv['title'];
            }
            $t2 = implode(',',$t2);
            $data[$k]['net_title'] = $t2;
            $data[$k]['net_json'] = json_encode($t);

        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //新增
    public function add(){
         $from=1;
        $this->assign("from",$from);
        $day=date("Y年m月");
        $this->assign("day",$day);
        if($_POST){
            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['jxs_id'] = $this->request->post('jxs_id');
            $ti_id = $this->request->post('ti_id');
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }
            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $data['attach'] = serialize(explode(',',$attach));
            }
            $savetype = $this->request->post('savetype');
            if($savetype=='save2'){
                $data['status'] = 3;//提交工作流
                $ys=$this->tiys($ti_id);
                if($ys===0){
                    echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
                }
                if($ys){
                    db("yusuan_detail")->insertAll($ys);
                }
                $flowId = db('cg_workflowset')->where(['id'=>'1'])->value('flow_id');

                $data2 = [];
                $data2['accessToken'] = session('accessToken');
                $data2['flowId'] = $flowId;
                $data2 = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$data2);
                $insert = [];
                $insert['ywlx'] = 1;
                $row = db('cg_ti')->where('id',$ti_id)->field('title,sn')->find();
                $insert['rwmcjbh'] = $row['title'].'['.$row['sn'].']';
                $insert['yw_id'] = $ti_id;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>session('employee_id')])->value('department_id');
                $insert['sqr_id'] = session('employee_id');
                $insert['workId'] = $data2->workId;
                $insert['trackId'] = $data2->flowNode->trackId;
                db('cg_workflow')->insert($insert);
            }
            $bool = Db::table('cg_ti')->where('id',$ti_id)->update($data);
            if(false !== $bool){
                //更新附件表
                if(isset($attachids)){
                    Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$ti_id,'target_table'=>'cg_ti'));
                }
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"添加成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"添加失败"
                ]);die;
            }

        }
        return $this->fetch('form');
    }

    //添加数据
    public function addData(){

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->where('method',null)->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fipay);

        //费用计入部门
        $fipay = db('cg_fijiruzd')->field('id,title')->select();
        $this->assign('fyjrbm',$fipay);

        //三级费用科目
        $feetype = db('cg_feiyongkemu3')->field('id,title')->where('esuseway','like','%"3"%')->select();
        $this->assign('feetype',$feetype);

        //计算年份
        $years = [];
        $year = intval(date('Y'));
        for($i=15;$i>-3;$i--){
            $years[] = $year+$i;
        }
        $this->assign('years',$years);

        return $this->fetch();
    }

    //生成编号
    public function produceSN(){
        //生成编号
        $max = db('cg_ti')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础
        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //提交整个费用项目
    public function appendRow(){

        $post = Request::instance()->post();

        //验证经销商id
        if(!isset($post['jxs_id'])||!$post['jxs_id']){
            echo  json_encode([
                "success"=>false,
                "msg"=>"请选择经销商"
            ]);die;
        }
        //验证单店销量
        foreach($post['danDianXiaoLiang'] as $k=>$v){
            $validate = new Valid([
                'd|单店销量'  => 'require|float',
            ]);
            $data = [];
            $data['d'] = $v;
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
        }

        //验证选择的网点
        if(!isset($post['selected_net'])||!$post['selected_net']){
            echo  json_encode([
                "success"=>false,
                "msg"=>"请选择网点"
            ]);die;
        }

        //验证本次进场条码
        if(!isset($post['selected_tiaoma'])||!$post['selected_tiaoma']){
            echo  json_encode([
                "success"=>false,
                "msg"=>"请选择本次进场条码"
            ]);die;
        }

        //验证其他基本字段
        $validate = new Valid([
            'year|进场年份'  => 'require',
            'month|进场月份'  => 'require',
            'head|负责人'  => 'require',
            'expCanTime|预计核销时间'  => 'require|dateFormat:Y-m-d',
            'paymethod|费用支付方式'  => 'require',
            'feetype|三级费用科目'  => 'require',
            'amount|未税总额'  => 'require|float',
            'isVAT|是否增值税'  => 'require',
            'shuilv|税率'  => 'require|float',
            'hanshui|含税总额'  => 'require|float',
            'fb_shijitourufeiyong|实际投入总额'  => 'require|float',
            'jrbm|费用计入部门'  => 'require',
        ]);
        if (!$validate->check($post)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }

        //验证条码明细
        foreach($post['f1'] as $k=>$v){
            $data = [];
            $data['f3'] = $post['f3'][$k];
            $data['f4'] = $post['f4'][$k];
            $data['f5'] = $post['f5'][$k];
            $validate = new Valid([
                'f3|经销商原价' => 'require',
                'f4|零售商供货价' => 'require',
                'f5|公司建议售价' => 'require',
            ]);
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            //验证零售商供货价和公司建议售价是否在既定范围内
            $jiage = db('pro_price')->where('pid',$v)->field('retail_low,retail_high,promotion_high,promotion_low')->find();
            if(($jiage['retail_low']&&$data['f4']<$jiage['retail_low'])||($jiage['retail_high']&&$data['f4']>$jiage['retail_high'])){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>'零售商供货价超过范围',
                    'overflow'=>1,
                    'pro_id'=>$v,
                ]);die;
            }elseif(($jiage['promotion_low']&&$data['f5']<$jiage['promotion_low'])||($jiage['promotion_high']&&$data['f5']>$jiage['promotion_high'])){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>'公司建议售价超过范围',
                    'overflow'=>2,
                    'pro_id'=>$v,
                ]);die;
            }

        }




        //如果主表存在
        if(isset($post['ti_id'])&&$post['ti_id']){
            $ti_id = $post['ti_id'];
            //查询主表编号
            $basic = db('cg_ti_list')->where('ti_id',$post['ti_id'])->max('sn'); //编号递增开始位置基础

        }else{ //如果主表不存在

            $insert_sn = $this->produceSN();//生成编号

            //生成ti
            $ti_id = db('cg_ti')->insertGetId([
                'cuser'=>session('employee_id'),
                'puser'=>session('employee_id'),
                'ctime'=>time(),
                'ptime'=>time(),
                'title'=>$post['title'],
                'jxs_id'=>$post['jxs_id'],
                'status'=>0,
                'sn'=>$insert_sn,
                'type_id'=>1,
            ]);
            $basic = 0; //编号递增开始位置基础
        }

        //验证结束后生成要插入的明细
        $insert = [];
        $post['expCanTime'] = strtotime($post['expCanTime']);
        $cnt = count($post['selected_net'])*count($post['f1']);
        $amount = round($post['amount']/$cnt,2); //拆分未税总额
        $hanshui = round($post['hanshui']/$cnt,2); //拆分含税总额
        $fb_shijitourufeiyong = round($post['fb_shijitourufeiyong']/$cnt,2); //拆分实际投入总额
        foreach($post['selected_net'] as $k=>$v){
            foreach($post['f1'] as $k1=>$v1){
                $basic++;
                $insert[] = [
                    'net_id'=>$v,
                    'net_ddxl'=>$post['danDianXiaoLiang'][$v],
                    'tm_id'=>$v1, //条码id（产品id)
                    'year'=>$post['year'],
                    'month'=>$post['month'],
                    'start'=>strtotime($post['year'].'-'.$post['month'].'-1'),
                    'end'=>strtotime($post['year'].'-'.$post['month'].'-1'),
                    'head'=>$post['head'],
                    'head_id'=>$post['head_id'],
                    'expCanTime'=>$post['expCanTime'],
                    'paymethod'=>$post['paymethod'],
                    'feetype'=>$post['feetype'],
                    'amount'=>$amount,
                    'pizhunweishui'=>$amount,
                    'fb_shijiweishui'=>$amount,
                    'shuilv'=>$post['shuilv'],
                    'hanshui'=>$hanshui,
                    'pizhunhanshui'=>$hanshui,
                    'yjsjtrfy'=>$fb_shijitourufeiyong,
                    'fb_shijitourufeiyong'=>$fb_shijitourufeiyong,
                    'jrbm'=>$post['jrbm'],
                    'project'=>$post['project'],
                    'isVAT'=>$post['isVAT'],
                    'ti_id'=>$ti_id,
                    'f1'=>$v1, //产品id
                    'f1_title'=>$post['f1_title'][$k1],
                    'f2'=>$post['f2'][$k1],
                    'f3'=>$post['f3'][$k1],
                    'f4'=>$post['f4'][$k1],
                    'f5'=>$post['f5'][$k1],
                    'sn'=>$basic,
                    'brief'=>$post['brief'],
                    'cuser'=>session('employee_id'),
                    'puser'=>session('employee_id'),
                    'ctime'=>time(),
                    'ptime'=>time(),
                ];
            }
        }

        db('cg_ti_list')->insertAll($insert);

        //明细table
        $str = $this->feeList($ti_id);

        echo  json_encode([
            "success"=>true,
            "data"=>$str,
            "ti_id"=>$ti_id,
        ]);die;

    }

    /**
     * @param $id ti_id
     * @param $arealat 区域纬度类型
     * @param $arealat_title 区域纬度标题
     * @param $productlat 产品纬度类型
     * @param $productlat_title 产品纬度标题
     * @param $jxs_id 经销商id
     * @param $jxs_title 经销商标题
     * @param $sn ti编号
     * @return string
     */
    public function feeList($id){
        $tijc = db('cg_ti')->where('id',$id)->field('sn,jxs_id')->find();
        $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();

        $zj_weishui = 0;
        $zj_hanshui = 0;
        $zj_shijitouru = 0;
        foreach($list as $k=>$v){
            $child = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
            $xj_weishui = 0;
            $xj_hanshui = 0;
            $xj_shijitouru = 0;
            foreach($child as $k1=>$v1){
                //查询产品系列
                $v1['series_name'] = db('pro_products t')->join('pro_sku t2','t2.id=t.sku_id')->join('pro_series t3','t3.id=t2.series_id')->where('t.id',$v1['f1'])->value('t3.series_name');
                $v1['expCanTime'] = date('Y-m-d H:i',$v1['expCanTime']);
                $v1['jiajialv1'] = round(($v1['f3']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv2'] = round(($v1['f4']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv3'] = round(($v1['f5']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v1['paymethod'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');
                $v1['isVAT'] = $v1['isVAT']==1?'是':'否';
                $v1['jrbm'] = db('department')->where('id',$v1['jrbm'])->value('de_name');
                $v1['project'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $xj_weishui += $v1['amount'];
                $xj_hanshui += $v1['hanshui'];
                $xj_shijitouru += $v1['fb_shijitourufeiyong'];
                $child[$k1] = $v1;
            }

            $v['_child'] = $child;
            $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
            $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.id');
            $v['system_nets'] = db('cg_net')->where('system_id',$system_id)->count(); //系统网点数
            $v['net_addr'] = db('cg_net')->where('id',$v['net_id'])->value('detailAddress'); //网点详细地址
            $v['net_cat'] = db('cg_networktype t')->join('cg_net t2','t2.cat=t.id')->where('t2.id',$v['net_id'])->value('t.title'); //网点类型
            $net_yjc = db('cg_net_barcode t')->join('pro_products t2','t2.id=t.prod')->where('t.net_id',$v['net_id'])->field('pro_name,is_repeat')->select();
            $tmp_arr = [];
            foreach($net_yjc as $kk=>$vv){
                $tmp_arr[] = ($vv['is_repeat']==1?'[重复进场]':'').$vv['pro_name'];
            }
            $tmp_arr = implode('</option><option>',$tmp_arr);
            $v['net_yjc'] = "<select style='height:50px;' multiple><option>"."{$tmp_arr}</option></select>";

            //小计-未税费用金额
            $v['xj_weishui'] = $xj_weishui;
            $v['xj_hanshui'] = $xj_hanshui;
            $v['xj_shijitouru'] = $xj_shijitouru;
            $list[$k] = $v;
            $zj_weishui += $xj_weishui;
            $zj_hanshui += $xj_hanshui;
            $zj_shijitouru += $xj_shijitouru;
        }

        $str = '';
        foreach($list as $k=>$v) {
            foreach ($v['_child'] as $k1 => $v1) {
                //查询f1是否重复进场
                $is_repeat = db('cg_net_barcode')->where(['prod'=>$v1['f1'],'net_id'=>$v1['net_id']])->count();
                $is_repeat = $is_repeat>=1?'(<font color=red>重复进场</font>)':'';
                $str .= <<<EOF
<tr data-id="{$v1['id']}">
                <td>
                    <button type="button" class="xiugai btn btn-outline btn-primary">修改</button>&nbsp;<button type="button" class="shanchu btn btn-outline btn-primary">删除</button>
                </td>
                <td>{$v1['sn']}</td>
                <td>{$tijc['sn']}-{$v1['sn']}</td>
                <td>{$v['system_title']}</td>
                <td>{$v1['head']}</td>
                <td>{$v['net_title']}</td>
                <td>{$v['system_nets']}</td>
                <td>待做</td>
                <td>{$v['net_addr']}</td>
                <td>{$v['net_cat']}</td>
                <td>{$v1['series_name']}</td>
                <td>{$v1['year']}年{$v1['month']}月</td>
                <td>{$v1['expCanTime']}</td>
                <td>{$v1['net_ddxl']}</td>
                <td>{$v['net_yjc']}</td>
                <td>{$is_repeat}{$v1['f1_title']}</td>
                <td>{$v1['f2']}</td>
                <td>{$v1['f3']}</td>
                <td>{$v1['jiajialv1']}%</td>
                <td>{$v1['f4']}</td>
                <td>{$v1['jiajialv2']}%</td>
                <td>{$v1['f5']}</td>
                <td>{$v1['jiajialv3']}%</td>
                <td>{$v1['feetype']}</td>
                <td>{$v1['paymethod']}</td>
                <td>{$v1['amount']}</td>
                <td>{$v1['isVAT']}</td>
                <td>{$v1['shuilv']}</td>
                <td>{$v1['hanshui']}</td>
                <td>{$v1['yjsjtrfy']}</td>
                <td>{$v1['jrbm']}</td>
                <td>{$v1['project']}</td>
                <td>{$v1['brief']}</td>
            </tr>
EOF;
            }

            $str .= <<<EOF
<tr>
                <td colspan="6" class="text-right">小计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right">{$v['xj_weishui']}</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right">{$v['xj_hanshui']}</td>
                <td class="text-right">{$v['xj_shijitouru']}</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
EOF;
        }
        $str .= <<<EOF
<tr>
                <td colspan="6" class="text-right">合计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right">{$zj_weishui}</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right">{$zj_hanshui}</td>
                <td class="text-right">{$zj_shijitouru}</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
EOF;

        return $str;
    }

    //修改数据行
    public function updateData(){
        $id = $this->request->get('id');

        if($_POST){

            $post = Request::instance()->post();

            //验证单店销量
            foreach($post['danDianXiaoLiang'] as $k=>$v){
                $validate = new Valid([
                    'd|单店销量'  => 'require|float',
                ]);
                $data = [];
                $data['d'] = $v;
                if (!$validate->check($data)) {
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$validate->getError()
                    ]);die;
                }
            }

            //验证选择的网点
            if(!isset($post['selected_net'])||!$post['selected_net']){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请选择网点"
                ]);die;
            }

            //验证本次进场条码
            if(!isset($post['selected_tiaoma'])||!$post['selected_tiaoma']){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请选择本次进场条码"
                ]);die;
            }

            //验证其他基本字段
            $validate = new Valid([
                'year|进场年份'  => 'require',
                'month|进场月份'  => 'require',
                'head|负责人'  => 'require',
                'expCanTime|预计核销时间'  => 'require|dateFormat:Y-m-d',
                'paymethod|费用支付方式'  => 'require',
                'feetype|三级费用科目'  => 'require',
                'amount|未税总额'  => 'require|float',
                'isVAT|是否增值税'  => 'require',
                'shuilv|税率'  => 'require|float',
                'hanshui|含税总额'  => 'require|float',
                'fb_shijitourufeiyong|实际投入总额'  => 'require|float',
                'jrbm|费用计入部门'  => 'require',
            ]);
            if (!$validate->check($post)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            //验证条码明细
            foreach($post['f1'] as $k=>$v){
                $data = [];
                $data['f3'] = $post['f3'][$k];
                $data['f4'] = $post['f4'][$k];
                $data['f5'] = $post['f5'][$k];
                $validate = new Valid([
                    'f3|经销商原价' => 'require',
                    'f4|零售商供货价' => 'require',
                    'f5|公司建议售价' => 'require',
                ]);
                if (!$validate->check($data)) {
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$validate->getError()
                    ]);die;
                }
            }


            $update = [
                'net_id'=>$post['selected_net'],
                'net_ddxl'=>$post['danDianXiaoLiang'][$post['selected_net']],
                'tm_id'=>$post['f1'][0], //条码id（产品id)
                'year'=>$post['year'],
                'month'=>$post['month'],
                'start'=>strtotime($post['year'].'-'.$post['month'].'-1'),
                'end'=>strtotime($post['year'].'-'.$post['month'].'-1'),
                'head'=>$post['head'],
                'head_id'=>$post['head_id'],
                'expCanTime'=>strtotime($post['expCanTime']),
                'paymethod'=>$post['paymethod'],
                'feetype'=>$post['feetype'],
                'amount'=>$post['amount'],
                'pizhunweishui'=>$post["amount"],
                'fb_shijiweishui'=>$post['amount'],
                'shuilv'=>$post['shuilv'],
                'hanshui'=>$post['hanshui'],
                'pizhunhanshui'=>$post['hanshui'],
                'fb_shijitourufeiyong'=>$post['fb_shijitourufeiyong'],
                'yjsjtrfy'=>$post['fb_shijitourufeiyong'],
                'jrbm'=>$post['jrbm'],
                'project'=>$post['project'],
                'isVAT'=>$post['isVAT'],
                'f1'=>$post['f1'][0], //产品id
                'f1_title'=>$post['f1_title'][0],
                'f2'=>$post['f2'][0],
                'f3'=>$post['f3'][0],
                'f4'=>$post['f4'][0],
                'f5'=>$post['f5'][0],
                'brief'=>$post['brief'],
                'cuser'=>session('employee_id'),
                'puser'=>session('employee_id'),
                'ctime'=>time(),
                'ptime'=>time()
            ];
            //修改其他
            $bool = db('cg_ti_list')->where('id',$post['mxid'])->update($update);
            if(false !== $bool){
//                echo db('cg_ti_list')->getLastSql();
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }
        }

        //查询非常规促销明细
        if($id){
            $list = db('cg_ti_list')->where('id',$id)->find();
            $list['net_title'] = db('cg_net')->where('id',$list['net_id'])->value('title');
            $list['tm_title'] = db('pro_products')->where('id',$list['tm_id'])->value('pro_name');
            $list['jrbm_title'] = db('department')->where('id',$list['jrbm'])->value('de_name');
            $this->assign('list',$list);
            //查询经销商id
            $jxs_id = db('cg_ti')->where('id',$list['ti_id'])->value('jxs_id');
            $this->assign('jxs_id',$jxs_id);

        }

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->where('method',null)->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fipay = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fipay);

        //费用计入部门
        $fipay = db('cg_fijiruzd')->field('id,title')->select();
        $this->assign('fyjrbm',$fipay);

        //三级费用科目
        $feetype = db('cg_feiyongkemu3')->field('id,title')->where('esuseway','like','%"3"%')->select();
        $this->assign('feetype',$feetype);

        //计算年份
        $years = [];
        $year = intval(date('Y'));
        for($i=15;$i>-3;$i--){
            $years[] = $year+$i;
        }
        $this->assign('years',$years);

        return $this->fetch();
    }

    //按照经销商返回网点树
    public function netTree(){
        $data = $this->request->param('keyword');
        $where = [];
        if($data){
            $systems = Db::table('cg_system_jxs')->where('jxs_id',$data)->field('system_id')->select();
            foreach($systems as $k=>$v){
                $systems[$k] = $v['system_id'];
            }
            $systems = implode(',',$systems);
            $where['system_id'] = ['in',$systems];
        }
        $data = Db::table('cg_net')->field('id,title name')->where($where)->select();
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['name'];
            $temp['id'] = $v['id'];
            $temp["chkDisabled"]=false;

            $where = [];
            $where['net_id'] = $v['id'];
            $where['tuichang'] = 0;
            $temp['yjctm'] = db('cg_net_barcode')->where($where)
                ->count();
            $temp['syxl'] = db('cg_net_barcode')->where($where)
                ->sum('shangYueXiaoLiang');
            $temp['link'] = url('net/view6',['id'=>$v['id']]);

            $data2[] = $temp;
        }
        echo json_encode($data2);
    }


    //添加费用项目行
    public function addFeiyong(){
        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay',$fipay);

        //费用计入方案
        $fijiru = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fijiru',$fijiru);

        $str = '';
        foreach($fipay as $k=>$v){
            $str .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
        $str2 = '';
        foreach($fijiru as $k=>$v){
            $str2 .= '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }

        $name = 'a'.mt_rand();
        echo <<<EOF
<tr class="data">
                <td>
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control feetype" name="feetype" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary feetree" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <input type="radio" name="{$name}" value="0" class="payee" checked>经销商&nbsp;
                    <input type="radio" name="{$name}" value="1" class="payee" disabled>供应商

                </td>
                <td><input type="text" name="amount" class="form-control"></td>
                <td>
                    <select name="paymethod"  class="form-control">
                        <option value="">请选择</option>
                        {$str}
                    </select>
                </td>
                <td>
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-xs-8">
                                <div class="input-group" >
                                    <input type="text" placeholder="请输入关键字或空格查询" class="form-control jrbm" name="jrbm" value="">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                        </ul>
                                    </div>
                                </div>
                                <div class="selectedOnlyOne " style="display:none;" >
                                    <span class="inin">f111</span>
                                    <span class="close">×</span>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <button class="btn btn-primary select_jrbm" >选择</button>
                            </div>
                        </div>
                    </div>
                </td>
                <td>
                    <select name="project" class="form-control">
                        <option value="">请选择</option>
                        {$str2}
                    </select>
                </td>
                <td class="text-center">
                    <button class="btn btn-danger del_fi_item" type="button">删除</button>
                </td>
            </tr>
EOF;

    }

    //生成反馈sn
    public function producefbSN(){
        //生成编号
        $max = db('all_ti_feeback_list')->where('no','like',date('Ymd').'%')->max('no'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //生成反馈sn
    public function producehxSN(){
        //生成编号
        $max = db('cg_ti_hexiao')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //单选本次进场条码
    public function dxbcjctm(){
        return $this->fetch();
    }
    //本次进场条码tree
    public function bcjctmtree(){
//        $yjc = $this->request->post('yjc');
//        $data = db('cg_net_barcode')->where('net_id','in',$yjc)->where(['tuichang'=>0])->column('prod');
////        echo db('cg_ti')->getLastSql();
//        $data = array_unique($data);
        $data = db('pro_products')->field('id,pro_name')->select();
        $li = [];
        foreach($data as $k=>$v){

            $price = db('pro_price')->where('pid',$v['id'])->field('retail_standard,factory')->find();
            $li[] = ['id'=>$v['id'],'name'=>$v['pro_name'],'factory'=>$price["factory"],'retail_standard'=>$price["retail_standard"]];
//            $li[] = "<li data-id='{$v}' data-factory='{$price["factory"]}' data-retail_standard='{$price["retail_standard"]}'>{$pro_name}</li>";
        }

        echo json_encode($li);
    }

    //多选本次进场条码
    public function selectMxbcjctm(){
        return $this->fetch();
    }

    //删除行
    /**
     * 修改附件--新增、修改申请时
     * @return mixed
     */
    private function updateAttach(){
        $attach = $this->request->post('attach');
        $id = $this->request->param('id');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = db('cg_ti')->where('id',$id)->value('attach');
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){
            $aids = array_diff($aids,explode(',',$remove));
            db('annex')->where('id','in',$remove)->update(['isdel'=>1]);
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        db('cg_ti')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){
            db('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti'));
        }

    }

    //删除本条
    public function delItem(){
        $ids = $this->request->param('ids');
        if(!$ids){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti_list')->where('id','in',$ids)->delete();
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
    /**
     * 修改附件--取消时
     * @return mixed
     */
    private function updateAttach2($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti')->where('id',$id)->value('attach');
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        Db::table('cg_ti')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti'));
        }

    }
    /**
     * 修改附件--核销
     * @return mixed
     */
    private function updateAttach3($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_ti_hexiao')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        Db::table('cg_ti_hexiao')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_ti_hexiao'));
        }

    }


    /**
     * 修改附件--反馈动作时
     * @return mixed
     */
    private function updateAttach_fb($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('all_ti_feeback_list')->where('id',$id)->value('fujian');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['fujian'] = $attach;
        Db::table('all_ti_feeback_list')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'all_ti_feeback_list'));
        }

    }
    public function baocunchuli(){
        if($_POST){
            $id=$this->request->post('ti_id');
            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['jxs_id'] = $this->request->post('jxs_id');
            if (!$validate->check($data)) {
               return json_encode(["msg" => $validate->getError(), "state" => 2]);
            }
            $list = $this->request->post('list');
            if(!$list){
                return json_encode(["msg" => "至少添加一条费用明细", "state" => 2]);
            }
            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $data['attach'] = serialize(explode(',',$attach));
            }
            $data['status'] = 3;//提交工作流
            $aid=$id;$ti_id=$id;

           // $bool = Db::table('cg_ti')->where('id',$id)->update($data);

            //修改附件
            $this->updateAttach();
            //echo 1;exit;
             Db::startTrans();
            try {
                $ys=$this->tiys($aid);$data["id"]=$aid;
                    if($ys===0&&$dataup["status"]==3)
                        return json_encode(["msg" => "尚未设定ti预算格式无法提交", "state" => 2]);
                $res1 = Db::table("cg_ti")->update($data);

               
                
                if($ys){
                    Db::table("yusuan_detail")->insertAll($ys);
                }
                    
               

            } catch (\Exception $e) {
                //echo $e->getMessage();
                Db::rollBack();
                return json_encode(["msg" => $e->getMessage(), "state" => 2]);
            }
            if ($res1) {
                $fid=1;
                $res=$this->goworker($fid,$aid,$this->request->post('nodeKey'),$this->request->post('selectId'),$this->request->post('selectName'));
               // print_r($res);exit;
                if($res["operateStatus"]=="success"){
                                Db::commit();
                                return json_encode(["msg"=>"","state"=>1]);
                            }else{
                                Db::rollBack();
                                return json_encode(["msg"=>$res->flowMsg,"state"=>2]);
                            }
            } else {
                Db::rollBack();
                return json_encode(["msg" => "系统繁忙请稍后再试", "state" => 2]);
            }

        }
    }
    /**
     * 修改基本信息
     * @return mixed
     * @throws \think\Exception
     */
    public function update($id,$from=1){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'title|主题'  => 'require|max:200',
                'jxs_id|经销商'  => 'require',
            ]);
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['jxs_id'] = $this->request->post('jxs_id');
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }
            $list = $this->request->post('list');
            if(!$list){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请添加至少一条数据"
                ]);die;
            }
            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $attach = $this->request->post('attach');
            if($attach){
                $attachids = $attach;
                $data['attach'] = serialize(explode(',',$attach));
            }
            $savetype = $this->request->post('savetype');
            if($savetype=='save2'){
                $data['status'] = 3;//提交工作流
                //$data['status'] = 3;//提交工作流
                $ys=$this->tiys($id);
                if($ys===0){
                    echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
                }
                if($ys){
                    db("yusuan_detail")->insertAll($ys);
                }
                $flowId = db('cg_workflowset')->where(['id'=>'1'])->value('flow_id');

                $data2 = [];
                $data2['accessToken'] = session('accessToken');
                $data2['flowId'] = $flowId;
                $data2 = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$data2);
                $insert = [];
                $insert['ywlx'] = 1;
                $row = db('cg_ti')->where('id',$id)->field('title,sn')->find();
                $insert['rwmcjbh'] = $row['title'].'['.$row['sn'].']';
                $insert['yw_id'] = $id;
                $insert['status'] = 1;
                $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>session('employee_id')])->value('department_id');
                $insert['sqr_id'] = session('employee_id');
                $insert['workId'] = $data2->workId;
                $insert['trackId'] = $data2->flowNode->trackId;
                db('cg_workflow')->insert($insert);
               
            }
            $bool = Db::table('cg_ti')->where('id',$id)->update($data);

            //修改附件
            $this->updateAttach();
            if(false !== $bool){

                //更新明细表
                if($list){
                    db('cg_ti_list')->where('id','in',$list)->update(['ti_id'=>$id]);
                }

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

        }

        $data = Db::table('cg_ti')->where('id',$id)->find();
        $day=date("Y年m月",$data["ctime"]);
        $this->assign("day",$day);
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $this->assign('data',$data);
        $this->assign('id',$id);
        $from=$this->request->param("from");
        if(!$from)
            $from=1;
        $this->assign("from",$from);
         if($data["status"]==2){
                    $btn=$this->getbton(1,$data["id"]);
                    //print_r($btn);exit;
                    $this->assign("btn",$btn);
                    $logs=$this->getlog($data["id"]);
                    //print_r($logs);
                    $this->assign("logs",$logs);
                }

        $str = $this->feeList($id);
        $this->assign('str',$str);


        //查询附件
        if($data['attach']){
            $attach = unserialize($data['attach']);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
            $this->assign('attach',$attach);
        }


        return $this->fetch('form');
    }

    //选择经销商
    public function selectJXS(){
        $this->assign('id',1);
        return $this->fetch();
    }

    /**
     * 删除
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_ti')->where(array('id'=>$id))->delete();
        if(false !== $bool){
            db('cg_ti_list')->where('ti_id',$id)->delete();
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    //选择费用科目3
    public function selectFee(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择费用计入部门
    public function selectJrbm(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择网点
    public function selectNet(){
        return $this->fetch();
    }
    //选择网点
    public function selectnetdx(){
        return $this->fetch();
    }
    //选择品牌
    public function selectBrands(){
        return $this->fetch();
    }
    //选择品类
    public function selectCategory(){
        return $this->fetch();
    }
    //选择系列
    public function selectSeries(){
        return $this->fetch();
    }
    //选择sku
    public function selectSKU(){
        return $this->fetch();
    }

    //选择单品
    public function selectProduct(){
        return $this->fetch();
    }
    //添加补货明细
    public function addbhlist(){
        if($_POST){
            dump($_POST);
            $data = $this->request->post('data/a');

            foreach($data as $k=>$v){
                $valid = new Valid([
                    'product|样品或物料'=>'require',
                    'num|数量'=>'require|number|>:0',
                ]);
                $bool = $valid->check($v);
                if(false==$bool){
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$valid->getError()
                    ]);die;
                }
            }
            die;
        }
        return $this->fetch();
    }

    //查看详情
    public function view(){
        $id = $this->request->param('id');
        $data = db('cg_ti')->where('id',$id)->find();
        if(!$data){
            return '参数错误';
        }
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        //经销商性质-直营
        $data['direct'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('direct');
//        申请人职位
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        //申请人部门
        $data['sjrbm'] = db('department_employee t')
            ->join('department t2','t2.id=t.department_id')
            ->where(['t.index'=>1,'employee_id'=>$data['cuser']])
            ->value('t2.de_name');

        //查询明细列表
        $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
        $wds = count($list); //网点数
        $this->assign('wds',$wds);
        foreach($list as $k=>$v){
            $v['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
            $v['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
            $v['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
            $v['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用

            $list[$k] = $v;
        }
        $zj_weishui = 0;
        $zj_hanshui = 0;
        $zj_shijitouru = 0;
        foreach($list as $k=>$v){
            $xj_weishui = 0;
            $xj_hanshui = 0;
            $xj_shijitouru = 0;
            foreach($v['_child'] as $k1=>$v1){

                $v1['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.title');
                $v1['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.id');
                $v1['system_net_num'] = db('cg_net')->where('system_id',$system_id)->count();
                $v1['net_addr'] = db('cg_net')->where('id',$v1['net_id'])->value('detailAddress');
                $v1['net_cat'] = db('cg_net t')->join('cg_networktype t2','t2.id=t.cat')->where('t.id',$v1['net_id'])->value('t2.title');
                $v1['product_series'] = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->join('pro_products t3','t3.sku_id=t2.id')->where('t3.id',$v1['f1'])->value('t.series_name');
                $sid = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->join('pro_products t3','t3.sku_id=t2.id')->where('t3.id',$v1['f1'])->value('t.id');
                $c = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sid)->value('t.category_name');
                $b = db('pro_brands t3')->join('pro_category t','t3.id=t.brand_id')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sid)->value('t3.brand_name');
                $v1['product_series'] = $b.'-'.$c.'-'.$v1['product_series'];
                $v1['unit'] = db('pro_products')->where('id',$v1['f1'])->value('unit');
                $v1['jiajialv1'] = round(($v1['f3']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv2'] = round(($v1['f4']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv3'] = round(($v1['f5']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v1['paymethod'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');
                $v1['isVAT'] = $v1['isVAT']==1?'是':'否';
                $v1['jrbm'] = db('department')->where('id',$v1['jrbm'])->value('de_name');
                $v1['project'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $xj_weishui += $v1['amount'];
                $xj_hanshui += $v1['hanshui'];
                $xj_shijitouru += $v1['fb_shijitourufeiyong'];
                $v['_child'][$k1] = $v1;
            }
            $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
            $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.id');
            $v['system_nets'] = db('cg_net')->where('system_id',$system_id)->count(); //系统网点数
            $v['net_addr'] = db('cg_net')->where('id',$v['net_id'])->value('detailAddress'); //网点详细地址
            $v['net_cat'] = db('cg_networktype t')->join('cg_net t2','t2.cat=t.id')->where('t2.id',$v['net_id'])->value('t.title'); //网点类型
            $net_yjc = db('cg_net_barcode t')->join('pro_products t2','t2.id=t.prod')->where('t.net_id',$v['net_id'])->column('pro_name');
            $net_yjc = array_unique($net_yjc);
            $net_yjc = implode('</option><option>',$net_yjc);
            $v['net_yjc'] = "<select style='height:50px;' multiple readonly><option>{$net_yjc}</option></select>";

            //小计-未税费用金额
            $v['xj_weishui'] = $xj_weishui;
            $v['xj_hanshui'] = $xj_hanshui;
            $v['xj_shijitouru'] = $xj_shijitouru;
            $list[$k] = $v;
            $zj_weishui += $xj_weishui;
            $zj_hanshui += $xj_hanshui;
            $zj_shijitouru += $xj_shijitouru;
            $list[$k] = $v;
        }

        $data['list'] = $list;
//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);
        $this->assign('zj_weishui',$zj_weishui);
        $this->assign('zj_hanshui',$zj_hanshui);
        $this->assign('zj_shijitouru',$zj_shijitouru);
        $feiarr=Db("cg_ti_list")->where(["ti_id"=>$id])->group("feetype")->field("feetype,sum(fb_shijitourufeiyong) as feiyong")->select();
        for($i=0;$i<count($feiarr);$i++){
            $feiarr[$i]["title"]=db("cg_feiyongkemu3")->where(["id"=>$feiarr[$i]["feetype"]])->value("title");
        }
        $this->assign("feiarr",$feiarr);
        $logs=$this->getlog($id);
        $this->assign("logs",$logs);
        $export = $this->request->get('export');
        if($export){

            //根据经销商查询分区省份和城市
            $city = db('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $provice = db('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $zoning = db('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $this->assign([
                'city'=>$city,
                'provice'=>$provice,
                'zoning'=>$zoning,
            ]);

            ob_end_clean();
            ob_start();

            header('Content-Type : application/vnd.ms-excel');
            header('Content-Disposition:attachment;filename="'.iconv('utf-8','gbk',$data['sn'].'-'.date("Y年m月j日")).'.xls"');
            return $this->fetch('view_export');
        }else{

            //查询核销编号
            $hxsn = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where('t3.ti_id',$id)
                ->field('t.id,t.sn')
                ->select();
            $this->assign('hxsn',$hxsn);
            //查询反馈编号
            $fbsn = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->where(['type'=>1,'t2.id'=>$id])
                ->field('t.id,t.no')
                ->find();
            $this->assign('fbsn',$fbsn);

            return $this->fetch();
        }
    }

    //经销商
    public function jxsview(){
        return $this->fetch();
    }
    //明细详情
    public function dataview(){
        $id = $this->request->param('id');
        $data = db('cg_ti_list')->where('id',$id)->find();
        $this->assign('data',$data);
        $apply=Db::table("cg_ti")->where(["id"=>$data["ti_id"]])->find();
        $this->assign("apply",$apply);
        $logs=$this->getlog($apply["id"]);
        $this->assign("logs",$logs);
        return $this->fetch();
    }
    //市场营销决策依据
    public function decisionbasis(){
        return $this->fetch();
    }

    //网点决策依据
    public function netjcYj(){
        return $this->fetch();
    }
    public function ROIjcyj(){
        return $this->fetch();
    }

    //提交工作流
    public function subworkflow(){
        $id = $this->request->param('id');
        db("cg_ti_list")->query("update cg_ti_list set pizhunweishui=amount,pizhunhanshui=hanshui where ti_id=$id");
        //echo $id;exit;
        $ys=$this->tiys($id);
        if($ys===0){
            echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
        }
        //echo json_encode(["msg" => "尚未设定ti预算格式无法提交", 'success'=>false]);die;
        $flowId = db('cg_workflowset')->where(['id'=>'1'])->value('flow_id');

        $data = [];
        $data['accessToken'] = session('accessToken');
        $data['flowId'] = $flowId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$data);
        $insert = [];
        $insert['ywlx'] = 1;
        $row = db('cg_ti')->where('id',$id)->field('title,sn')->find();
        $insert['rwmcjbh'] = $row['title'].'['.$row['sn'].']';
        $insert['yw_id'] = $id;
        $insert['status'] = 1;
        $insert['department_id'] = db('department_employee')->where(['index'=>1,'employee_id'=>session('employee_id')])->value('department_id');
        $insert['sqr_id'] = session('employee_id');
        $insert['workId'] = $data->workId;
        $insert['trackId'] = $data->flowNode->trackId;
        db('cg_workflow')->insert($insert);
        if($ys){
            Db::table("yusuan_detail")->insertAll($ys);
       }
        $bool = db('cg_ti')->where('id',$id)->update(['status'=>3]);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'提交成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'提交失败']);
        }
    }
    //提交工作流
    public function shenhe(){
        $id = $this->request->param('id');
        $ti = db('cg_ti')->where('id',$id)->field('cate_id,title,jxs_id,attach')->find();
        if($ti['cate_id']==3){ //如果申请类型为2，代表取消，则生成新的取消后剩余未取消的新单
            $old = db('cg_ti')->where('id',$id)->value('old');
            //首先生成新的编号
            $newsn = $this->produceSN();
            //生成新的主表记录
            $insert = [
                'sn'=>$newsn,
                'title'=>$ti['title'],
                'jxs_id'=>$ti['jxs_id'],
                'attach'=>$ti['attach'],
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>7, //7已归档
                'old'=>$old,
                'cate_id'=>1, //类型,1正常申请
                'type_id'=>1,
            ];
            $new_ti_id = db('cg_ti')->insertGetId($insert);
            $oldids = db('cg_ti_list')->where('ti_id',$old)->column('id');
            $qxids = db('cg_ti_list')->where('ti_id',$id)->column('refer_id');
            $wqxids = array_diff($oldids,$qxids);
            $wqxmx = db('cg_ti_list')->where('id','in',$wqxids)->select();
            foreach($wqxmx as $k=>$v){
                $v['ti_id'] = $new_ti_id;
                $v['ctime'] = time();
                $v['ptime'] = time();
                $v['cuser'] = Session::get('employee_id');
                $v['puser'] = Session::get('employee_id');
                $v['ti_id'] = $new_ti_id;
                $v['status'] = 0;
                $v['refer_id'] = $v['id'];//对应的原单
                unset($v['id']);
                $wqxmx[$k] = $v;
            }
            db('cg_ti_list')->insertAll($wqxmx);
        }

        //插入网点进场条码表
        $aaa = db('cg_ti_list')->where('ti_id',$id)->field('tm_id,net_id,fb_shijitourufeiyong,f4')->select();
        foreach($aaa as $k=>$v){
            $cnt = db('cg_net_barcode')->where(['net_id'=>$v['net_id'],'prod'=>$v['tm_id']])->count();
            if($cnt>0){
               $is_repeat = 1;
            }else{
                $is_repeat = 0;
            }
            db('cg_net_barcode')->insert([
                'prod'=>$v['tm_id'],
                'intime'=>time(),
                'infee'=>$v['fb_shijitourufeiyong'],
                'retailPrice'=>$v['f4'],
                'net_id'=>$v['net_id'],
                'isdel'=>0,
                'tuichang'=>0,
                'is_repeat'=>$is_repeat
            ]);

        }

        $bool = db('cg_ti')->where('id',$id)->update(['status'=>7]);
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'通过成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'通过失败']);
        }
    }

    //根据id查找状态
    public function status($id){
        $data = [
            1=>'草稿',
            2=>'已打回',
            3=>'区域领导审批',
            4=>'拆分人审批',
            5=>'集团领导审批',
            6=>'抄送',
            7=>'已归档',
            8=>'已作废',
            9=>'已否决',
        ];
        return $data[$id];
    }

    //根据id查找产品纬度标题
    public function productlat($id){
        $data = [
            1=>'品牌',
            2=>'品类',
            3=>'系列',
            4=>'SKU',
            5=>'单品',
        ];
        return $data[$id];
    }

    //取消
    public function cancel(){
        $id = $this->request->param('id');

        //提交表单
        if($_POST){

            //原单保持原样，取消的部分和未取消的部分分别生成新单
            $post_data = $this->request->post('data/a');
            $type = $this->request->post('type');

            //验证
            $ids = [];
            foreach($post_data as $k=>$v){

                if(trim($v['reason'])==''){
                    echo json_encode(['success'=>false,'msg'=>'请填写取消原因']);die;
                }
                $ids[] = $v['id'];

            }

            $ti = db('cg_ti')->where('id',$id)->find();
            //生成新的取消申请单
            $newSN = $this->produceSN();
            $insert = [
                'sn'=>$newSN,
                'title'=>$ti['title'],
                'jxs_id'=>$ti['jxs_id'],
                'attach'=>$ti['attach'],
                'ctime'=>time(),
                'ptime'=>time(),
                'cuser'=>Session::get('employee_id'),
                'puser'=>Session::get('employee_id'),
                'status'=>0,
                'old'=>$id,
                'cate_id'=>3, //类型,3取消
                'type_id'=>1,
            ];
            if($type=='save2'){
                $insert['status']=3; //提交工作流，区域领导审批
            }
            $bool = true;
            //生成新的取消后申请单
            $new_ti_id = db('cg_ti')->insertGetId($insert);

            //修改附件
            $this->updateAttach2($new_ti_id);

            //生成新的取消后明细
            $insert = [];
            foreach($post_data as $k=>$v){
                $row = db('cg_ti_list')->where('id',$v['id'])->find();
                $row['ctime'] = time();
                $row['ptime'] = time();
                $row['cuser'] = Session::get('employee_id');
                $row['puser'] = Session::get('employee_id');
                $row['ti_id'] = $new_ti_id;
                if(trim($v['reason'])){
                    $row['cancel_reason'] = $v['reason'];
                }

                $row['status'] = 2;//0正常，2已取消
                $row['refer_id'] = $row['id'];//对应的原单
                unset($row['id']);
                $insert[] = $row;
            }

            $temp_bool = db('cg_ti_list')->insertAll($insert);
            if($temp_bool===false)
                $bool = false;
            //原单子标记为取消
            $temp_bool = db('cg_ti')->where('id',$id)->update(['new'=>$new_ti_id,'status2'=>2]);
            if($temp_bool===false)
                $bool = false;
            if(false!==$bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }

        $data = db('cg_ti')->where('id',$id)->find();
        if(!$data){
            return '参数错误';
        }
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        //经销商性质-直营
        $data['direct'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('direct');
//        申请人职位
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        //申请人部门
        $data['sjrbm'] = db('department_employee t')
            ->join('department t2','t2.id=t.department_id')
            ->where(['t.index'=>1,'employee_id'=>$data['cuser']])
            ->value('t2.de_name');

        //查询明细列表
        $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
        $wds = count($list); //网点数
        $this->assign('wds',$wds);
        foreach($list as $k=>$v){
            $v['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
            $v['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
            $v['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
            $v['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用

            $list[$k] = $v;
        }
        $zj_weishui = 0;
        $zj_hanshui = 0;
        $zj_shijitouru = 0;
        foreach($list as $k=>$v){
            $xj_weishui = 0;
            $xj_hanshui = 0;
            $xj_shijitouru = 0;
            foreach($v['_child'] as $k1=>$v1){

                $v1['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.title');
                $v1['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.id');
                $v1['system_net_num'] = db('cg_net')->where('system_id',$system_id)->count();
                $v1['net_addr'] = db('cg_net')->where('id',$v1['net_id'])->value('detailAddress');
                $v1['net_cat'] = db('cg_net t')->join('cg_networktype t2','t2.id=t.cat')->where('t.id',$v1['net_id'])->value('t2.title');
                $v1['product_series'] = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->join('pro_products t3','t3.sku_id=t2.id')->where('t3.id',$v1['f1'])->value('t.series_name');
                $sid = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->join('pro_products t3','t3.sku_id=t2.id')->where('t3.id',$v1['f1'])->value('t.id');
                $c = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sid)->value('t.category_name');
                $b = db('pro_brands t3')->join('pro_category t','t3.id=t.brand_id')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sid)->value('t3.brand_name');
                $v1['product_series'] = $b.'-'.$c.'-'.$v1['product_series'];
                $v1['unit'] = db('pro_products')->where('id',$v1['f1'])->value('unit');
                $v1['jiajialv1'] = round(($v1['f3']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv2'] = round(($v1['f4']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv3'] = round(($v1['f5']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v1['paymethod'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');
                $v1['isVAT'] = $v1['isVAT']==1?'是':'否';
                $v1['jrbm'] = db('department')->where('id',$v1['jrbm'])->value('de_name');
                $v1['project'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $xj_weishui += $v1['amount'];
                $xj_hanshui += $v1['hanshui'];
                $xj_shijitouru += $v1['fb_shijitourufeiyong'];
                $v['_child'][$k1] = $v1;
            }
            $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
            $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.id');
            $v['system_nets'] = db('cg_net')->where('system_id',$system_id)->count(); //系统网点数
            $v['net_addr'] = db('cg_net')->where('id',$v['net_id'])->value('detailAddress'); //网点详细地址
            $v['net_cat'] = db('cg_networktype t')->join('cg_net t2','t2.cat=t.id')->where('t2.id',$v['net_id'])->value('t.title'); //网点类型
            $net_yjc = db('cg_net_barcode t')->join('pro_products t2','t2.id=t.prod')->where('t.net_id',$v['net_id'])->column('pro_name');
            $net_yjc = array_unique($net_yjc);
            $net_yjc = implode('</option><option>',$net_yjc);
            $v['net_yjc'] = "<select style='height:50px;' multiple readonly><option>{$net_yjc}</option></select>";

            //小计-未税费用金额
            $v['xj_weishui'] = $xj_weishui;
            $v['xj_hanshui'] = $xj_hanshui;
            $v['xj_shijitouru'] = $xj_shijitouru;
            $list[$k] = $v;
            $zj_weishui += $xj_weishui;
            $zj_hanshui += $xj_hanshui;
            $zj_shijitouru += $xj_shijitouru;
            $list[$k] = $v;
        }

        $data['list'] = $list;
//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);
        $this->assign('zj_weishui',$zj_weishui);
        $this->assign('zj_hanshui',$zj_hanshui);
        $this->assign('zj_shijitouru',$zj_shijitouru);

        //查询附件
        $attach = Db::table('cg_ti')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db::table('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);
        return $this->fetch();
    }

    //roi报告
    public function roireport(){
        return $this->fetch();
    }

    //返回二维数组中的某二维key的合计
    public function array_sum($arr,$key){
        $sum = 0;
        foreach($arr as $k=>$v){
            $sum += $v[$key];
        }
        return $sum;
    }

    //查看流程图
    public function workflowchart(){
        $id = $this->request->param('id');
        $workId = db('cg_workflow')->where(['ywlx'=>1,'yw_id'=>$id])->value('workId');
        $trackId = db('cg_workflow')->where(['ywlx'=>1,'yw_id'=>$id])->value('trackId');dump($workId);dump($trackId);
        header('location:'.config('workflow_url').'/workflow/module/workflow/flow.info.html?workId='.$workId.
            '&trackId='.$trackId);
    }

    //搜索网点
    public function search_net(){
        $net_id = $this->request->post('net_id');
        $net = db('cg_net')->where('id',$net_id)->value('title');

        //查询已进场的条码：
        $yjc = db('cg_net_barcode t')->join('pro_products t2','t2.id=t.prod')->where('t.net_id',$net_id)->column('t2.pro_name');
        $str = '<form method="get" class="form-inline" style="margin:10px"><h2 class="title_color padding-10 text-center" style="font-size:20px">'.$net.'*,已进场条码</h2><table class="table-bordered table row-margin-top">';
        foreach($yjc as $k=>$v){
            $str .= '<tr><td style="width:100px" class="text-right">'.($k+1).'</td><td>'.$v.'</td></tr>';
        }

        $str .= '</table><p class="padding-10 text-right"><a href="'.url('net/view6',['id'=>$net_id]).'" class="J_menuItem">点击管理已进场条码</a></p></form>';
        echo $str;
    }
}
